
#include <stdlib.h>
#include <iostream>
#include "RouterTable.h"
#include "EntryRT.h"

RouterTable::RouterTable(int serial_number, int number_of_nodes) {
	_owner_serial_number	= serial_number;
	_number_of_nodes		= number_of_nodes;
	init_table(serial_number, number_of_nodes);
}

RouterTable::~RouterTable() {
	cout << "~RouterTable" << endl;
	for (unsigned int i = 0; i < _table->size(); ++i) {
		cout << "del " << i << endl;
		delete(_table->at(i));
	}
	delete(_table);
}

void RouterTable::re_init_table()
{
	for (int i = 1; i < size(); ++i) {
		((EntryRT*)_table->at(i))->setDistance(INFINITY);
		((EntryRT*)_table->at(i))->setNext_hop(EMPTY_SET);
	}

	// update owner's entry:
	((EntryRT*)_table->at(_owner_serial_number))->setDistance(0);
	((EntryRT*)_table->at(_owner_serial_number))->setNext_hop(_owner_serial_number);
}

void RouterTable::init_table(int serial_number, int number_of_nodes)
{
	_table = new vector<EntryRT*>();

	// initialize all entries:
	//(entry in place 0 in the vector is dummy, because worker 0 doesn't exist)
	_table->push_back(NULL);
	for (int i = 1; i < number_of_nodes+1; ++i) {
		_table->push_back(new EntryRT(i, INFINITY, EMPTY_SET));
	}

	// update owner's entry:
	((EntryRT*)_table->at(serial_number))->setDistance(0);
	((EntryRT*)_table->at(serial_number))->setNext_hop(serial_number);
}

EntryRT *RouterTable::get_entry(int worker_number)
{
	return _table->at(worker_number);
}

int RouterTable::size()
{
	return _table->size();
}

void RouterTable::print()
{
	bool printing_allowed = false;
	if ( printing_allowed )
	{
		cout << endl << "Target  Distance  Next-Hop" << endl;
		for (int i = 1; i < _number_of_nodes+1; ++i) {
			int target	 = get_entry(i)->getTarget();
			int distance = get_entry(i)->getDistance();
			int next_hop = get_entry(i)->getNext_hop();
			cout << target << "       ";
			if ( distance == INFINITY )
				cout << "oo" << "         ";
			else
				cout << distance << "         ";

			if ( next_hop == EMPTY_SET )
				cout << "Q";
			else
				cout << next_hop;

			cout << endl;
		}
	}
}
